package com.allwees.support.marketing.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.allwees.support.marketing.dao.AdjustPriceRuleDao;
import com.allwees.support.marketing.domain.AdjustPriceRule;
import com.allwees.support.marketing.dto.AdjustProductPriceDTO;
import com.allwees.support.marketing.event.PriceRuleUpdatedEvent;
import com.allwees.support.marketing.service.AdjustPriceRuleService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @Author Daniel
 * @Version 1.0.0
 * @Description
 * @CreateTime 2020/9/1 10:05
 */
@Service
public class AdjustPriceRuleServiceImpl extends ServiceImpl<AdjustPriceRuleDao,AdjustPriceRule> implements AdjustPriceRuleService {

    @Resource
    private AdjustPriceRuleDao adjustPriceRuleDao;

    @Resource
    protected ApplicationContext context;

    @Transactional
    @Override
    public int saveRule(AdjustProductPriceDTO dto) {
        return adjustPriceRuleDao.insert(dto.toSaveEntity());
    }

    @Transactional
    @Override
    public int updateRule(AdjustProductPriceDTO dto) {
        int rows = adjustPriceRuleDao.updateById(dto.toUpdateEntity());
        if(rows > 0){
            context.publishEvent(PriceRuleUpdatedEvent.get());
        }
        return rows;
    }

    @Transactional
    @Override
    public int enableRule(Long id) {
        AdjustPriceRule rule = adjustPriceRuleDao.selectById(id);
        if(rule == null || rule.getStatus() == 0){
            return 0;
        }
        rule = new AdjustPriceRule();
        rule.setId(id);
        rule.setStatus(0);

        int rows = adjustPriceRuleDao.updateById(rule);
        if(rows > 0){
            context.publishEvent(PriceRuleUpdatedEvent.get());
        }
        return rows;
    }

    @Transactional
    @Override
    public int disableRule(Long id) {
        AdjustPriceRule rule = adjustPriceRuleDao.selectById(id);
        if(rule == null || rule.getStatus() == 1){
            return 0;
        }
        rule = new AdjustPriceRule();
        rule.setId(id);
        rule.setStatus(1);
        int rows = adjustPriceRuleDao.updateById(rule);
        if(rows > 0){
            context.publishEvent(PriceRuleUpdatedEvent.get());
        }
        return rows;
    }
}
